<script setup lang="ts">
import { reactive, ref, onMounted, h } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import {
  getSystemConfigList,
  editSystemConfig,
  addSystemConfig
} from "@/api/system";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { PureTableBar } from "@/components/RePureTableBar";

import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { addDialog } from "@/components/ReDialog/index";
import editForm from "./form.vue";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import type { FormItemProps } from "@/views/system/menu/utils/types";
import { message } from "@/utils/message";

import { omit } from "lodash-es";

defineOptions({
  name: "ConfigSettings"
});
const dialogFormRef = ref();
const loading = ref(true);
const dataList = ref([]);
const tableRef = ref();
const formRef = ref();
const form = reactive({
  functionName: "",
  remark: "",
  key: ""
});
form["备注"] = null;
form["函数名称"] = null;
const isShow = ref(false);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});

function onFullscreen() {
  // 重置表格高度
  tableRef.value.setAdaptive();
}

function handleSizeChange(val: number) {
  pagination.pageSize = val;
  onSearch();
}

function handleCurrentChange(val: number) {
  pagination.currentPage = val;
  onSearch();
}

function resetForm(formEl) {
  console.log("formEl:", formEl); // 看是否是 undefined
  console.log("formEl.value:", formEl?.value); // 看 ref 是否正确
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
}

async function onSearch() {
  // loading.value = true;
  const { data, total } = await getSystemConfigList({
    // action:"?"
    action: "public/filter_bi_sjfw",

    key: form.key,
    // csbm:"",
    // hsmc: form["备注"],
    // 后端pageIndex，pageSize 要求是string 格式
    pageIndex: String(pagination.currentPage),
    pageSize: String(pagination.pageSize)
    // 函数名称: form["函数名称"],
    // 备注: form["备注"]
  });
  pagination.total = total;
  dataList.value = data;

  loading.value = false;
}

const columns = [
  {
    label: "函数名称",
    prop: "函数名称",
    width: 100
  },
  {
    label: "参数编码",
    prop: "参数编码",
    width: 100
  },
  {
    label: "参数名称",
    prop: "参数名称",
    width: 200
  },
  {
    label: "参数值",
    prop: "参数值"
  },

  {
    label: "备注",
    prop: "备注"
  },
  {
    label: "操作",
    fixed: "right",
    slot: "operation",
    width: 100
  }
];

function openDialog(title = "新增", row?: any) {
  if (!row) {
    row = {}; // 默认空对象
  }
  addDialog({
    title: `${title}参数`,
    props: {
      formInline: {
        id: row["序号"] ?? null,
        configCode: row["参数编码"] ?? "",
        configValue: row["参数值"] ?? "",
        functionName: row["函数名称"] ?? "",
        name: row["参数名称"] ?? "",
        remark: row["备注"] ?? ""
      }
    },
    width: "45%",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () =>
      h(editForm, { ref: dialogFormRef, formInline: null }),
    beforeSure: (done, { options }) => {
      const FormRef = dialogFormRef.value.getFormRef(); // 获取 el-form 实例
      const curData = options.props.formInline as FormItemProps;
      console.log(curData);

      function chores() {
        message(`您${title}了函数名称为${curData.functionName}的这条数据`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      }

      FormRef.validate(valid => {
        if (valid) {
          const _data = cloneDeep(curData) as Partial<FormItemProps>;

          if (title === "新增") {
            addSystemConfig(_data).then(res => {
              if (res.code === 0) chores();
            });
          } else {
            editSystemConfig(_data.id, _data).then(res => {
              if (res.code === 0) chores();
            });
          }
        }
      });
    }
  });
}

onMounted(() => {
  onSearch();
});
</script>
<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="搜索条件：" prop="key">
        <el-input
          v-model="form.key"
          placeholder="请输入搜索条件"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <!--      <el-form-item label="备注：" prop="备注">-->
      <!--        <el-input-->
      <!--          v-model="form['备注']"-->
      <!--          placeholder="请输入备注"-->
      <!--          clearable-->
      <!--          class="w-[180px]!"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <PureTableBar
      :class="[isShow && !deviceDetection() ? 'w-[60vw]!' : 'w-full']"
      style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)"
      title="取值参数设置 "
      :columns="columns"
      @refresh="onSearch"
      @fullscreen="onFullscreen"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog()"
        >
          新增
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          row-key="id"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('修改', row)"
            >
              修改
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-table__inner-wrapper::before) {
  height: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
